/*******************************************************************************
 * Copyright (c) 2008 Smart Mai(smardio@gmail.com).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Smart Mai(smardio@gmail.com) - initial API and implementation
 ******************************************************************************/
package com.smartdio.company.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;

import com.smartdio.company.editor.PersonEditor;
import com.smartdio.company.editor.PersonInput;
import com.smartdio.company.model.Person;
import com.smartdio.company.views.PersonView;

/**
 * @author smart
 * 
 */
public class EditPerson extends AbstractHandler implements IHandler {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.
	 * ExecutionEvent)
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// 先获得PersonView视图
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		IWorkbenchPage page = window.getActivePage();
		PersonView view = (PersonView) page.findView(PersonView.ID);
		TableViewer viewer = view.getViewer();
		// 获得选择的对象
		ISelection selection = viewer.getSelection();
		if (selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			// 如果选择的对象没有问题，那么就打开编辑器
			if (obj != null) {
				Person person = (Person) obj;
				PersonInput input = new PersonInput(person);
				try {
					page.openEditor(input, PersonEditor.ID);
					viewer.setSelection(viewer.getSelection());
				} catch (PartInitException e) {
				}
			}
		}
		return null;

	}

}
